package com.example.demo.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.custom.AjaxResult;
import com.example.demo.entity.Insurance;
import com.example.demo.entity.Insurance2;
import com.example.demo.form.InsuranceForm2;
import com.example.demo.service.Insurance2Service;
import com.example.demo.service.InsuranceService;

@RestController
@RequestMapping(value = "/Insurance2")
public class Insurance2Controller {
	@Autowired
	private InsuranceService service1;
	@Autowired
	private Insurance2Service service2;
	
	private DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");

	@RequestMapping(value = "/save")
	private Object save(InsuranceForm2 Form) throws ParseException {
		Integer insid1=Form.getId();
		Date d=new Date();
		Date d1=dateFormat1.parse("1999-01-01");
		Insurance ins=new Insurance();
		Insurance Ins=new Insurance();
		Insurance2 ins2=new Insurance2();
		Insurance2 Ins2=new Insurance2();
		if(insid1==null) {
			Ins.setName(Form.getName());
			ins=service1.save(Ins);
		}else {
			ins=service1.findById(insid1);
			ins.setName(Form.getName());
			service1.save(ins);
			List<Insurance2> list=service2.findByInsurance(ins);
			for(Insurance2 insurance2:list) {
				if(d1.compareTo(insurance2.getBeginDate())==-1) {
					d1=insurance2.getBeginDate();
					Ins2=insurance2;
				}
			}
			Ins2.setEndDate(d);
			service2.save(Ins2);
		}
		BeanUtils.copyProperties(Form, ins2, "id","name");
		ins2.setInsurance(ins);
		ins2.setBeginDate(d);
		service2.save(ins2);
		return new AjaxResult("数据保存成功");
	}
	
	@RequestMapping(value = "/list")
	private Object list() {
		return new AjaxResult(service1.findAll());
	}
	
	@RequestMapping(value = "/findbyId")
	private Object findbyId(Integer id) throws ParseException {
		List<Insurance2> list=service2.findByInsuranceId(id);
		DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
		Date d=dateFormat.parse("1999-01-01");
		Insurance2 ins=new Insurance2();
		for(Insurance2 y:list) {
			if(d.compareTo(y.getBeginDate())==-1) {
				d=y.getBeginDate();
				ins=y;
			}
		}
		return new AjaxResult(ins);
	}
}
